﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using QQ.Util;
using System.Threading;
using RuoTeng.Util;
using System.Windows.Forms;

namespace RTGather.Lib.gather
{

    /// <summary>
    ///ClickBank 专用采集类
    ///
    /// </summary>
    public class fbb_ClickBank
    {

        private string countpattern = @"(?isx)Displaying\sresults\s1-10\sout\sof\s(?<count>.*?)\(";//总条数 
        //================================================================ 

        private string areapattern = @"(?isx)<tr\sclass=.result.>(?<inner>.*?)</tr>";//块

        private string Pidpattern = @"(?isx)zzzzz.(?<pid>.*?).hop.clickbank.net";//Pid 

        private string descpattern = @"(?isx)class=.description.>(?<desc>.*?)</div>";//描述

        private string titlePattern = @"(?isx)hop.clickbank.net\u0022\starget=._blank.>(?<title>.*?)</a>";//标题 


        private string codeurlPattern = @"(?isx)<p>.*<br/>(?<url>.*?)\s*</p>";//推广code 

        private static string rootpath = Application.StartupPath;//根目录

        private string oldgather = rootpath + "\\已采集产品.txt";

        private List<Product> clist = new List<Product>();

        public void getData(string url,string code,string format)
        {

            string html=Http.GetData(url, null);
                       
            MatchCollection matches = Regex.Matches(html, areapattern);
            clist.Clear();
            
            foreach (Match match in matches)
            {
                string innerurl = "";
                GroupCollection groups = match.Groups;

                if (groups.Count > 0)
                {

                    innerurl = groups["inner"].ToString();  
                    string pname = getStrFromPattern(titlePattern, innerurl, "title"); 
                    string pid = getStrFromPattern(Pidpattern, innerurl, "pid");
                    string desc = getStrFromPattern(descpattern, innerurl, "desc"); 
                    Product p = new Product();
                    p.desc = desc;
                    if (desc == "没有登记")
                    {
                        p.desc = pname;
                    } 
                    if (IsRepeat(pid, oldgather) == false)
                    {
                        p.Name = pname;
                        p.Pid = pid;
                        p.vcode = makeCode(code, pid, pname, format);
                        writeNew(pid, oldgather);
                        clist.Add(p);
                    } 
                }

            }
        }


        /// <summary>
        /// 判断是否重复
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private bool IsRepeat(string url, string filename)
        {
            List<string> list = TextBoxTools.getFileList(filename);
            bool isrepeat = list.Contains(url);
            return isrepeat;
        }


        /// <summary>
        /// 写入新的记录
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="filename"></param>
        private void writeNew(string pid, string filename)
        {
            string old = RTFile.ReadFile(filename);
            string newstring = old + pid + System.Environment.NewLine;
            RTFile.WriteFile(filename, newstring);

        }
         
        public string getStrFromPattern(string pattern,string content,string name)
        {
            Match match = Regex.Match(content, pattern);
            string result="";
            if (match.Success)
            {
                GroupCollection groups = match.Groups;
                result = groups[name].ToString();
            }
            else
            {
                result = "没有登记";
            }
            return result; 
        }



        public string makeCode(string code, string pid, string title,string format)
        {

            string url = "https://www.clickbank.com/hoplink_encoding.htm";

            string post = string.Format("affiliate={0}&vendor={1}&searchButton=Encode",code,pid);

            string resulthtml = Http.GetData(url, post, null);


            string urltem = getStrFromPattern(codeurlPattern, resulthtml, "url");

            string result = string.Format("<a href=\"{0}\" target=\"_top\"> More </a>", urltem);

            return result;
        }

        /// <summary>
        /// 根据关键词搜索提取条数
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public int getCount(string keyword)
        {
            string url = string.Format("https://www.clickbank.com/buy_products.htm?dores=true&includeKeywords={0}", keyword);

            string result = Http.GetData(url, null);

            string count = getStrFromPattern(countpattern, result, "count");
            count = count.Replace(",", "");

            int num = 0;

            if (count != "没有登记")
            {
                num = ParseType.ParseInt(count, 0);
            } 
            return num;
        }

        /// <summary>
        /// 计算页数 
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public int getPageCount(int count)
        {

            int PageSize = 20;

            int pagenum = (count / PageSize) + 1;

            return pagenum;

        }


        /// <summary>
        /// 导出 文件excel
        /// </summary>
        /// <param name="filename"></param>
        public void ExcelExport(string filename)
        {
            Excel.Application xls_app = null;
            Excel._Workbook xls_book = null;
            Excel._Worksheet xls_sheet = null;
            System.Reflection.Missing miss = System.Reflection.Missing.Value;
            try
            {
                xls_app = new Excel.ApplicationClass();
                xls_app.Visible = false;
                Excel.Workbooks workBooks = (Excel.Workbooks)xls_app.Workbooks;
                if (!System.IO.File.Exists(filename))
                {
                    xls_book = (Excel.Workbook)workBooks.Add(true);
                    Excel.Sheets _sheets = xls_book.Sheets;
                    xls_sheet = (Excel.Worksheet)_sheets[1];
                    int columnIndex = 1;

                    xls_sheet.Cells[1, columnIndex] = "产品编号"; columnIndex++; 
                    xls_sheet.Cells[1, columnIndex] = "产品标题"; columnIndex++; 
                   xls_sheet.Cells[1, columnIndex] = "产品描述"; columnIndex++;  
                    xls_sheet.Cells[1, columnIndex] = "产品代码"; columnIndex++; 
                   
                   
                    xls_book.SaveAs(filename, miss, miss, miss, miss, miss, Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss, miss, miss);
                    xls_book.Close(false, miss, miss);

                }
                xls_book = workBooks.Open(filename, miss, miss, miss, miss, miss, Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss, miss, miss);
                Excel.Sheets sheets = xls_book.Sheets;
                xls_sheet = (Excel.Worksheet)sheets[1];

                int rowIndex = xls_sheet.UsedRange.Rows.Count == 0 ? 1 : xls_sheet.UsedRange.Rows.Count + 1;

                foreach (Product c in this.clist)
                {

                    int columnIndex = 1;

                    xls_sheet.Cells[rowIndex, columnIndex] = c.Pid;
                    columnIndex++;


                    xls_sheet.Cells[rowIndex, columnIndex] = c.Name;
                    columnIndex++;

                    xls_sheet.Cells[rowIndex, columnIndex] = c.desc;
                    columnIndex++;

                    xls_sheet.Cells[rowIndex, columnIndex] = c.vcode;
                    columnIndex++;

                    rowIndex++;

                }
                xls_book.Save();
                xls_book.Close(false, miss, miss);
                xls_app.Quit();
            }
            catch(Exception ex) { if (xls_book != null) { xls_book.Save(); xls_book.Close(false, miss, miss); xls_app.Quit(); } }
        }


    }
}
